/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 * Origin source from MaNGOS(GPL2).
 * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/>
 */

#include "Config.h"
#include "ace/Configuration_Import_Export.h"

namespace PQServiceCore
{
	static bool getValueHelper(ACE_Configuration_Heap *config, const char *name, ACE_TString &result)
	{
		if (!config){
			return false;
		}
		ACE_TString section_name;
		ACE_Configuration_Section_Key section_key;
		ACE_Configuration_Section_Key root_key = config->root_section();

		int i = 0;
		while (config->enumerate_sections(root_key, i, section_name) == 0){
			config->open_section(root_key, section_name.c_str(), 0, section_key);
			if (config->get_string_value(section_key, name, result) == 0){
				return true;
			}
			++i;
		}

		return false;
	}


	Config& Config::getSingleton()
	{
		static Config inst;
		return inst;
	}


	Config::Config()
	: _config(NULL)
	{
	}

	Config::~Config()
	{
		delete _config;
	}

	bool Config::setSource(const char *file)
	{
		_filename = file;

		return reload();
	}

	bool Config::reload()
	{
		delete _config;
		_config = new ACE_Configuration_Heap;

		if (_config->open() == 0)
		{
			ACE_Ini_ImpExp config_importer(*_config);
			if (config_importer.import_config(_filename.c_str()) == 0)
				return true;
		}

		delete _config;
		_config = NULL;
		return false;
	}

	std::string Config::getStringDefault(const char* name, const char* def)
	{
		ACE_TString val;
		return getValueHelper(_config, name, val) ? val.c_str() : def;
	}

	bool Config::getBoolDefault(const char* name, bool def)
	{
		ACE_TString val;
		if (!getValueHelper(_config, name, val))
			return def;

		const char* str = val.c_str();
		if (strcmp(str, "true") == 0 || strcmp(str, "TRUE") == 0 ||
			strcmp(str, "yes") == 0 || strcmp(str, "YES") == 0 ||
			strcmp(str, "1") == 0)
			return true;
		else
			return false;
	}


	int32 Config::getIntDefault(const char* name, int32 def)
	{
		ACE_TString val;
		return getValueHelper(_config, name, val) ? atoi(val.c_str()) : def;
	}


	float Config::getFloatDefault(const char* name, float def)
	{
		ACE_TString val;
		return getValueHelper(_config, name, val) ? (float)atof(val.c_str()) : def;
	}
}
